#!/bin/bash
images_db=registry.cn-hangzhou.aliyuncs.com/veops/cmdb-db:2.3
images_redis=registry.cn-hangzhou.aliyuncs.com/veops/cmdb-cache:2.3
images_api=registry.cn-hangzhou.aliyuncs.com/veops/cmdb-api:2.4.14
images_ui=registry.cn-hangzhou.aliyuncs.com/veops/cmdb-ui:2.4.14
src_pwd=`pwd`
src_data=/data/docker/cmdb

# Set Passwd
mysql_root_pd="ptb@3xDnHPF7^"


# Set Web Port
NginxPortHost=80


#
#
# Create Network
docker network rm cmdb
docker network create --subnet 172.20.88.0/24 cmdb
if [[ $? -eq 0 ]];then
	echo "Network Create Ok"
else
	echo "Network Create Failed"
	exit 2
fi
v=" -v ${src_data}/docker_mysql_data:/var/lib/mysql:rw -v ${src_pwd}/docs/mysqld.cnf:/etc/mysql/conf.d/mysqld.cnf:rw -v ${src_pwd}/docs/cmdb.sql:/docker-entrypoint-initdb.d/cmdb.sql "
e=" -e MYSQL_HOST=172.20.88.10 -e MYSQL_ROOT_PASSWORD=${mysql_root_pd} -e MYSQL_DATABASE=cmdb -e MYSQL_USER=cmdb -e MYSQL_PASSWORD=${mysql_root_pd} "
cmd="docker run -tid --name cmdb-db ${e} ${v} --net=cmdb --ip 172.20.88.10 ${images_db}"
echo $cmd
$cmd
if [[ $? -eq 0 ]];then
	echo "Db Runing"
else
	echo "Db Not Running"
	exit 2
fi
# Init Sql
docker cp ${src_pwd}/docker-mysql.sh cmdb-db:/
docker exec -ti cmdb-db /bin/bash -c "chmod 0777 /docker-mysql.sh;/docker-mysql.sh"

# Create Redis
docker run -tid --name cmdb-cache -v ${src_data}/redis:/data/:rw --net=cmdb --ip 172.20.88.20 ${images_redis}
if [[ $? -eq 0 ]];then
	echo "Redis Runing"
else
	echo "Redis Not Running"
	exit 3
fi

# Create Api
docker run -tid --name cmdb-api -v ${src_pwd}/docker-api.sh:/docker-api.sh ${e} -e TZ="Asia/Shanghai" -e WAIT_HOSTS="cmdb-db:3306,cmdb-cache:6379" --net=cmdb --ip 172.20.88.30 ${images_api}
if [[ $? -eq 0 ]];then
	echo "Api Service Is Ok"
else
	echo "Api Service Not Running"
	exit 2
fi

# Creare Ui
v=" -v ${src_pwd}/docs/nginx.cmdb.conf.example:/etc/nginx/conf.d/nginx.cmdb.conf.example -v ${src_pwd}/docker-ui.sh:/docker-ui.sh "
e=" -e TZ="Asia/Shanghai" -e CMDB_API_HOST="cmdb-api:5000" -e NGINX_PORT=80 "
docker run -tid -p ${NginxPortHost}:80 --name cmdb-ui ${v} ${e}  --net=cmdb --ip 172.20.88.40  ${images_ui} /docker-ui.sh
if [[ $? -eq 0 ]];then
	echo "Ui Service Is Ok"
else
	echo "Ui Service Not Running"
	exit 2
fi
